<?php

namespace app\admin\service\user_profile\userArchive\evaluationArchive;

use app\admin\controller\Task;
use app\admin\service\UserService;
use app\common\Message;
use app\model\ProxyEvaluationResultModel;
use app\model\SelfEvaluationResultModel;
use app\model\TaskModel;
use app\model\TaskUserModel;
use app\model\TaskUserResultModel;
use app\model\UserModel;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\db\Query;
use think\Service;

class EvaluationArchiveService extends Service
{
    use Message;

    /**
     * 测评档案概况
     * @param $data
     * @return true
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getOverview($data): bool
    {
        //用户基本信息
        $info = $this->getUserInfo($data);
        //测评报告数据统计
        $selfEvaluationResultModel = new SelfEvaluationResultModel(); //自我测评
        $taskUserResultModel = new TaskUserResultModel(); //任务测评
        $proxyEvaluationResultModel = new ProxyEvaluationResultModel();//他人测评
        if(check_array_key('isAbandon',$data)){
            //废弃档案
            $tempWhere = [
                ['uid','=',$data['user_id']],
                ['is_repeal','=',1],
            ];
        }else{
            //正常档案
            $tempWhere = [
                ['uid','=',$data['user_id']],
                ['is_repeal','=',0],
            ];
        }
        $selfEvaluationResult = $selfEvaluationResultModel->where($tempWhere)->field('id,is_warning,time')->select();
        $taskUserResult = $taskUserResultModel->where($tempWhere)->field('id,is_warning,time')->select();
        $proxyEvaluationResult = $proxyEvaluationResultModel->where($tempWhere)->field('id,is_warning,time')->select();
        $totalCount = count($selfEvaluationResult)+count($taskUserResult)+count($proxyEvaluationResult);
//        if($totalCount>0){
            $ret = [
//                'min_time' => 0,//档案首次建立时间
//                'to_date' => 0,//距今天数
                'total' => $totalCount,//所有报告总数
                'self' => count($selfEvaluationResult), //自我测评报告总数
                'task' => count($taskUserResult), //任务测评
                'proxy' => count($proxyEvaluationResult), //他人测评
                'wireless' => 0, //无线测评
                'waring'=>0, //预警总数
                'waring_proportion' =>0, //预警占比
                'waring_self' =>0, //自我测评预警数
                'waring_self_proportion' =>0, //自我测评预警占比
                'waring_task' =>0, //任务测评预警数
                'waring_task_proportion' =>0, //任务测评预警占比
                'waring_proxy' =>0, //他人测评预警数
                'waring_proxy_proportion' =>0, //他人测评预警占比
                'waring_wireless' =>0, //无线测评预警数
                'waring_wireless_proportion' =>0, //无线测评预警占比
            ];
//            if($totalCount>0){
                // 统计各类预警数
                foreach (['self' => $selfEvaluationResult,'task' => $taskUserResult,'proxy' => $proxyEvaluationResult] as $key => $results) {
                    foreach ($results as $item) {
                        if ($item['is_warning'] == 1) {
                            $ret["waring_$key"]++;
                        }
                    }
                }
                $ret['waring'] = $ret['waring_self']+$ret['waring_task']+$ret['waring_proxy'];
                if($ret['waring']>0){
                    $ret['waring_proportion'] = removeTrailingZero(number_format($ret['waring'] / $ret['waring'] * 100, 1));
                    if($ret['self'] == 0){
                        $ret['waring_self_proportion'] = 0;
                    }else{
                        $ret['waring_self_proportion'] = removeTrailingZero(number_format($ret['waring_self'] / $ret['waring'] * 100, 1));
                    }
                    if($ret['task'] == 0){
                        $ret['waring_task_proportion'] = 0;
                    }else{
                        $ret['waring_task_proportion'] = removeTrailingZero(number_format($ret['waring_task'] / $ret['waring'] * 100, 1));
                    }
                    if($ret['proxy'] == 0){
                        $ret['waring_proxy_proportion'] = 0;
                    }else{
                        $ret['waring_proxy_proportion'] = removeTrailingZero(number_format($ret['waring_proxy'] / $ret['waring'] * 100, 1));
                    }
                }
                $tempArray = array_merge($selfEvaluationResult->toArray(),$taskUserResult->toArray(),$proxyEvaluationResult->toArray());
                $timeArray = array_column($tempArray, 'time');
                if (!empty($timeArray)){
                    $ret['min_time'] = min($timeArray);
                    $ret['max_time'] = max($timeArray);
                    $ret['to_date'] = ceil((time() - $ret['min_time']) / (24 * 60 * 60));
                }else{
                    $ret['min_time'] = 0;
                    $ret['max_time'] = 0;
                    $ret['to_date'] = 0;
                }
//            }
            $info['archives'] = $ret;
//        }else{
//            $info = [];
//        }
        $this->result = $info;
        $this->message = '操作成功！';
        return true;
    }

    /**
     * 获取用户基本信息
     * @param $data
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getUserInfo($data): array
    {
        $where = [
            ['id','=',$data['user_id']],
        ];
        $field = ['id,name,username,sex,province_name,age,phone,nation,city_name,area_name,department_id,unit_id,
        user_number,time,student_status','role_mode','update_time'];
        $list = UserModel::query()->where($where)->with(['departmentNameMode' => function($query){
            $query->with(['departmentLevel']);
        },'unitName'])->field($field)->find();
        //用户基本信息
        $info['user_info'] = '';
        if(!empty($list)){
            if(!empty($list['level_rules'])){
                $list['level_rules'] = json_decode($list['level_rules']);
                if($list['level_rules']){
                    $list['level_rules_name'] = $list['level_rules'][$list['department_stage']];
                }
            }
            $UserService = new UserService($this->app);
            $DepartmentAdminAll = $UserService->getDepartmentAdminAll($list['department_id']);
            $DepartmentAffiliationAll = $UserService->getDepartmentAffiliationAll($data['unit_id']);
            $list['department_name'] = $DepartmentAffiliationAll[$list['department_id']]['all_name']??'';
            $list['department_admin'] = $DepartmentAdminAll[$list['department_id']]['user_name']??'';
            $list['student_status'] = empty($list['student_status'])?0:$list['student_status'];
            $info['user_info'] = $list;
        }
        return $info;
    }

    /**
     * 自我测评记录
     * @param $data
     * @return true
     * @throws DbException
     */
    public function getSelfRecode($data): bool
    {
        $selfEvaluationResultModel = new SelfEvaluationResultModel(); //自我测评
        if(check_array_key('isAbandon',$data)){
            //废弃档案
            $where = [
                ['uid','=',$data['user_id']],
                ['is_repeal','=',1],
            ];
        }else{
            //正常档案
            $where = [
                ['uid','=',$data['user_id']],
                ['is_repeal','=',0],
            ];
        }
        $return = $selfEvaluationResultModel->where($where)
            ->with(['ratingScale'=>function($query){
                $query->with(['ratingScaleTypeName']);
            }])
            ->field('id,rating_scale_id,is_warning,time,result_read_auth')
            ->select();
        $ret = [];
        if(count($return)>0){
            $ret = $this->sort_by_month($return->toArray(),'time',$data);
        }
        $this->result = $ret;
        $this->message = '操作成功！';
        return true;
    }

    /**
     * 按年月分页排序（倒序）.[一个月算一条数据]
     * @param $arr
     * @param $field
     * @param $data
     * @return array
     */
    public function sort_by_month($arr, $field, $data): array
    {
        $warningCount = 0;
        $groupedItems = [];
        // 按月份分组并计算预警数量
        foreach ($arr as $item) {
            $month = date('Y-m', $item[$field]); // 提取年份和月份
            $groupedItems[$month][] = $item; // 添加到对应的月份
            if (isset($item['is_warning']) && $item['is_warning'] == 1) {
                $warningCount++;
            }
        }
        // 为每个月的数据按时间倒序排序
        foreach ($groupedItems as &$items) {
            usort($items, function ($a, $b) use ($field) {
                return $b[$field] <=> $a[$field]; // 倒序排序
            });
        }
        // 将结果按月份倒序输出
        krsort($groupedItems);
        // 合并所有数据
        $merged_data = [];
        foreach ($groupedItems as $month => $tasks) {
            $merged_data = array_merge($merged_data, $tasks);
        }
        //排序从1开始
        $total = count($merged_data);
        foreach($merged_data as $key=>&$temp){
            $temp['number'] = $total-$key;
        }
        // 将 $merged_data 还原为 $groupedItems 数据结构
        $groupedItems = [];
        foreach ($merged_data as $item) {
            // 获取任务的结束时间，转化为月份字符串
            $month_key = date('Y-m', $item[$field]);
            // 如果该月份不存在，初始化一个数组
            if (!isset($groupedItems[$month_key])) {
                $groupedItems[$month_key] = [];
            }
            // 添加任务到相应月份数组中
            $groupedItems[$month_key][] = $item;
        }
        // 分页处理，并添加预警数信息
        $result = paginateArray($groupedItems, $data['page'], $data['pageSize']);
        $result['meta']['warning_num'] = $warningCount;
        $result['meta']['recode_total'] = count($arr);
        return $result;
    }


    /**
     * 任务测评记录
     * @param $data
     * @return true
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getTaskRecode($data): bool
    {
        $taskUserResult = new TaskUserResultModel();
        if(check_array_key('isAbandon',$data)){
            //废弃档案
            $tempWhere = [
                ['uid','=',$data['user_id']],
                ['is_repeal','=',1],
            ];
        }else{
            //正常档案
            $tempWhere = [
                ['uid','=',$data['user_id']],
                ['is_repeal','=',0],
            ];
        }
        $return = $taskUserResult->where($tempWhere)->with([
            'task'
        ])->field('id,task_id,1 as rating_scale_count,time as end_time,is_warning')->select()->toArray();
        foreach ($return as &$item) {
            $item['name'] = $item['task_name'];
        }
        $ret = $this->sort_by_month($return,'end_time',$data);
        $this->result = $ret;
        $this->message = '操作成功！';
        return true;
    }
    /**
     * 他人测评记录
     * @param $data
     * @return true
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getProxyRecode($data): bool
    {
        $proxy_evaluation_result = new ProxyEvaluationResultModel();
        if(check_array_key('isAbandon',$data)){
            //废弃档案
            $where = [
                ['uid','=',$data['user_id']],
                ['is_repeal','=',1],
            ];
        }else{
            //正常档案
            $where = [
                ['uid','=',$data['user_id']],
                ['is_repeal','=',0],
            ];
        }
        $return = $proxy_evaluation_result->where($where)
            ->with(['ratingScale'=>function($query){
                $query->with(['ratingScaleTypeName']);
            },'ProxyUser'])
            ->field('id,rating_scale_id,is_warning,time,proxy_uid,result_read_auth')
            ->select();
        $ret = [];
        if(count($return)>0){
            $ret = $this->sort_by_month($return->toArray(),'time',$data);
        }
        $this->result = $ret;
        $this->message = '操作成功！';
        return true;
    }



}